#include "../EventLoop.h"
#include "../TcpClient.h"
#include "../TcpConnection.h"
#include "../Channel.h"

using namespace std::placeholders;

class TestClient
{
public:
    TestClient(EventLoop* loop, const string& ip, const int port)
        : loop_(loop)
        , client_(loop, ip, port)
        , stdinChannel_(loop, 0)
    {
        client_.setConnectionCallback(std::bind(&TestClient::onConnection, this, _1));
        client_.setMessageCallback(std::bind(&TestClient::onMessage, this, _1, _2));

        stdinChannel_.setReadCallback(std::bind(&TestClient::handleRead, this));
        stdinChannel_.enableReading();
    }

    void connect(){
        client_.connect();
    }

private:
    void onConnection(const TcpConnectionPtr& conn) {
        std::cout << "TestClient::onConnection" << std::endl;
    }

    void onMessage(const TcpConnectionPtr& conn, Buffer* buf) {
        std:string msg(buf->retrieveAllAsString());
        std::cout << "client get : " << msg << std::endl;
    }

    void handleRead()
    {
        std::cout << "stdin handleRead\n";
        char buf[1024] = {0};
        fgets(buf, 1024, stdin);
        // buf[strlen(buf)-1] = '\0';
        client_.connection()->send(buf);
    }

    EventLoop* loop_;
    TcpClient client_;
    Channel stdinChannel_;
};

int main () {
    // int numThreads = 4;

    EventLoop loop;

    std::string ip = "127.0.0.1";
    int port = 12345;

    TestClient client(&loop, ip, port);
    client.connect();

    loop.loop();

    return 0;
}

// g++ -std=c++17 main.cpp ../*.cpp  -lpthread -o client